<template>
  <div class="layout">
    <div class="main-box">
      <div class="tit">生产计划记录</div>

      <div class="searcher-box">
        <div class="inp">
          <div class="inpH">开始时间</div>
          <el-date-picker
            v-model="startDate"
            type="datetime"
            placeholder="选择开始时间"
            class="picker"
            value-format="YYYY-MM-DD HH:mm:ss"
          >
          </el-date-picker>
        </div>
        <div class="inp">
          <div class="inpH">结束时间</div>
          <el-date-picker
            v-model="endDate"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          >
          </el-date-picker>
        </div>
        <div class="inp">
          <div class="inpH">合金牌号</div>
          <el-autocomplete
            :style="{ width: '220px' }"
            v-model="modelName"
            :fetch-suggestions="querySearch1"
            placeholder="请输入合金牌号"
            @select="handleSelect"
          >
            <template #default="{ item }">
              {{ item.modelName }}
            </template>
          </el-autocomplete>
        </div>
        <el-button
          type="primary"
          icon="search"
          style="width: 80px"
          @click="handleSearch"
        >
          查询
        </el-button>
        <el-button
          type="primary"
          icon="refresh"
          style="width: 80px"
          @click="reset"
        >
          重置
        </el-button>
      </div>

      <div class="btn-list">
        <div class="left-btns">
          <el-button
            type="primary"
            v-if="search == true"
            class="ret"
            @click="handleReturn"
            icon="House"
            >返回</el-button
          >
          <el-button
            v-else
            type="primary"
            icon="plus"
            style="width: 100px; margin-right: 6px"
            @click="dialogFormVisible = true"
          >
            添加
          </el-button>
          <el-button icon="delete" @click="handleDelete" type="danger"> 删除 </el-button>
          <el-button icon="refresh" @click="handleRefresh" type="success">
            刷新
          </el-button>
        </div>
      </div>

      <div class="table-box">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          height="540"
          @selection-change="handleSelectionChange"
          :default-sort="{ prop: 'createdAt', order: 'descending' }"
          class="custom-table"
        >
          <el-table-column fixed type="selection" width="40" />
          <el-table-column label="合金牌号" width="150">
            <template #default="scope">
              <el-link type="text" @click="handleConcrete1(scope?.row)">{{
                scope?.row.modelName
              }}</el-link>
              <span
                :style="{ color: 'green' }"
                v-if="scope?.row.isQuantityBased == 0"
                >(按件数计)</span
              >
              <span :style="{ color: 'blue' }" v-else>(按重量计)</span>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="70">
            <template #default="scope">
              <span v-if="scope?.row.isQuantityBased == 0">产品</span>
              <span v-else>材料</span>
            </template>
          </el-table-column>
          <el-table-column label="形态" width="70">
            <template #default="scope">
              <span v-if="scope?.row.isSpecificationType != 7">{{
                dy[scope?.row.isSpecificationType]
              }}</span>
              <span v-else>其他</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="plannedQuantity"
            label="总需求量"
            width="110"
            sortable
          >
          </el-table-column>
          <el-table-column
            prop="remainingQuantity"
            label="剩余需求量"
            width="120"
            sortable
          >
          </el-table-column>
          <el-table-column prop="status" label="计划状态" width="90">
          </el-table-column>
          <el-table-column prop="specification" label="规格" width="170">
          </el-table-column>
          <el-table-column label="关联开炉记录" width="80">
            <template #default="scope">
              <el-button
                type="primary"
                plain
                size="small"
                @click.stop="handleConcrete(scope?.row)"
                >详情</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="createdAt"
            label="创建时间"
            width="170"
            sortable
          >
          </el-table-column>
          <el-table-column
            prop="updatedAt"
            label="更新时间"
            width="170"
            sortable
          >
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150">
            <template #default="scope">
              <el-button
                type="primary"
                plain
                size="small"
                @click.stop="handleEdit(scope?.row)"
                >编辑</el-button
              >
              <el-button
                type="primary"
                plain
                size="small"
                @click.stop="handleStore(scope?.row)"
                >入库</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-box">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleRefresh"
          v-if="search == false"
          v-model:current-page="pageNum"
          :page-sizes="[30]"
          v-model:page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          prev-text="上一页"
          next-text="下一页"
        >
        </el-pagination>
      </div>

      <el-dialog
        title="创建生产计划"
        v-model="dialogFormVisible"
        :before-close="reset1"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        draggable
      >
        <div class="form-box">
          <div class="col">
            <div class="ys">
              <div class="wz">合金牌号</div>
              <el-autocomplete
                :style="{ width: '280px' }"
                v-model="form.modelName"
                :fetch-suggestions="querySearch1"
                placeholder="请输入合金牌号"
                @select="handleSelect1"
                clearable
              >
                <template #default="{ item }">
                  {{ item.modelName }}
                </template>
              </el-autocomplete>
            </div>
            <div class="ys">
              <div class="wz">生产类型</div>
              <el-select
                v-model="form.isQuantityBased"
                :style="{ width: '280px' }"
                placeholder="请选择生产类型"
              >
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
          <div class="col">
            <div class="ys">
              <div class="wz">需求总量</div>
              <el-input
                class="sr"
                placeholder="请输入需求量"
                v-model="form.plannedQuantity"
                clearable
              >
              </el-input>
            </div>
            <div class="ys">
              <div class="wz">规格(选填)</div>
              <el-autocomplete
                :style="{ width: '280px' }"
                v-model="form.specification"
                :fetch-suggestions="showAllSuggestions"
                placeholder="请输入规格号"
                @select="handleSelect3"
                clearable
                trigger-on-focus
              >
                <template #default="{ item }">
                  <div>{{ item }}</div>
                </template>
              </el-autocomplete>
            </div>
          </div>
          <div class="col">
            <div class="ys">
              <div class="wz">备注(选填)</div>
              <el-input
                placeholder="请输入计划备注(非必填项)"
                v-model="form.note"
                class="sr"
                clearable
              >
              </el-input>
            </div>
          </div>
          <div class="relate">
            <el-select
              v-model="form.isSpecificationType"
              :style="{ width: '150px', margin: '10px' }"
              placeholder="请选择物品形态"
              @change="handleChange(form)"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-alert title="规格可选择形态后点击生成也可以直接在上输入" type="success" class="tip" :closable="false"/>
            <div
              class="sp"
              v-if="
                form.isSpecificationType != '' && form.isSpecificationType != 7
              "
            >
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('D')"
              >
                <div class="wz wz2">直/外径</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.D"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('d')"
              >
                <div class="wz wz2">内径</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.d"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('L')"
              >
                <div class="wz wz2">长度</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.L"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('W')"
              >
                <div class="wz wz2">宽度</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.W"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('T')"
              >
                <div class="wz wz2">厚度</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.T"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('Φ')"
              >
                <div class="wz wz2">偏心直径</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.Φ"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{
                  width: '10%',
                  margin: '0 10px',
                  display: 'flex',
                  justifyContent: 'flex-start',
                }"
              >
                <el-button type="primary" @click="pj(form)">生成规格</el-button>
              </div>
            </div>
          </div>
          <div class="relate">
            <el-popover placement="left" :width="400" trigger="click">
              <template #reference>
                <el-button style="margin-right: 16px" @click="relate(form)"
                  >选择关联开炉记录</el-button
                >
              </template>
              <el-table
                :data="gridData"
                @row-click="handleRowClick1"
                :height="250"
              >
                <el-table-column
                  prop="furnaceNumber"
                  label="炉号"
                  width="120"
                />
                <el-table-column
                  prop="furnaceDate"
                  label="生产时间"
                  width="150"
                >
                </el-table-column>
                <el-table-column prop="modelName" label="合金牌号" width="120">
                </el-table-column>
              </el-table>
            </el-popover>
            <el-alert title="非必选" type="info"  class="tip" style="width:10%;height:30px" :closable="false"/>
            <div class="col">
              <div class="ys">
                <div class="wz">熔炼炉号</div>
                <el-input
                  class="sr"
                  placeholder="熔炼炉号"
                  v-model="form.furnaceRecord.furnaceNumber"
                  disabled
                >
                </el-input>
              </div>
              <div class="ys">
                <div class="wz">生产日期</div>
                <el-input
                  class="sr"
                  placeholder="开炉生产日期"
                  v-model="form.furnaceRecord.furnaceDate"
                  disabled
                >
                </el-input>
              </div>
            </div>
            <div class="col">
              <div class="ys">
                <div class="wz">总投入量</div>
                <el-input
                  class="sr"
                  placeholder="原材料总投入量"
                  v-model="form.furnaceRecord.totalConsumed"
                  disabled
                >
                </el-input>
              </div>
              <div class="ys">
                <div class="wz">总产出量</div>
                <el-input
                  class="sr"
                  placeholder="熔炼总产出量"
                  v-model="form.furnaceRecord.output"
                  disabled
                >
                </el-input>
              </div>
            </div>
            <div class="col">
              <div class="ys">
                <div class="wz">平均损耗</div>
                <el-input
                  class="sr"
                  placeholder="熔炼平均损耗"
                  v-model="form.furnaceRecord.avgLoss"
                  disabled
                >
                </el-input>
              </div>
              <div class="ys">
                <div class="wz">产出率</div>
                <el-input
                  class="sr"
                  placeholder="熔炼产出率"
                  v-model="form.furnaceRecord.outputRatio"
                  disabled
                >
                </el-input>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitA">确 定</el-button>
          <el-button @click="reset1">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="修改生产计划"
        v-model="dialogFormVisible1"
        :before-close="reset2"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        draggable
      >
        <div class="form-box">
          <div class="col">
            <div class="ys">
              <div class="wz">合金牌号</div>
              <el-autocomplete
                :style="{ width: '280px' }"
                v-model="edit1.modelName"
                :fetch-suggestions="querySearch1"
                placeholder="请输入合金牌号"
                @select="handleSelect2"
                clearable
              >
                <template #default="{ item }">
                  {{ item.modelName }}
                </template>
              </el-autocomplete>
            </div>
            <div class="ys">
              <div class="wz">生产类型</div>
              <el-select
                v-model="edit1.isQuantityBased"
                :style="{ width: '280px' }"
                placeholder="请选择生产类型"
              >
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
          <div class="col">
            <div class="ys">
              <div class="wz">总需求量</div>
              <el-input
                class="sr"
                placeholder="请输入需求量"
                v-model="edit1.plannedQuantity"
                clearable
              >
              </el-input>
            </div>
            <div class="ys">
              <div class="wz">规格(选填)</div>
              <el-autocomplete
                :style="{ width: '280px' }"
                v-model="edit1.specification"
                :fetch-suggestions="showAllSuggestions1"
                placeholder="请输入规格"
                @select="handleSelect4"
                clearable
                trigger-on-focus
              >
                <template #default="{ item }">
                  <div>{{ item }}</div>
                </template>
              </el-autocomplete>
            </div>
          </div>
          <div class="col">
            <div class="ys">
              <div class="wz">备注(选填)</div>
              <el-input
                class="sr"
                placeholder="请输入备注(非必填)"
                v-model="edit1.note"
                clearable
              >
              </el-input>
            </div>
          </div>
          <div class="relate">
            <el-select
              v-model="edit1.isSpecificationType"
              :style="{ width: '150px', margin: '10px' }"
              placeholder="请选择产品类型"
              @change="handleChange(edit1)"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-alert title="规格可选择形态后点击生成也可以直接在上输入" type="success" class="tip" :closable="false"/>
            <div
              class="sp"
              v-if="
                edit1.isSpecificationType != null &&
                edit1.isSpecificationType != 7
              "
            >
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('D')"
              >
                <div class="wz wz2">直/外径</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.D"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('d')"
              >
                <div class="wz wz2">内径</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.d"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('L')"
              >
                <div class="wz wz2">长度</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.L"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('W')"
              >
                <div class="wz wz2">宽度</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.W"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('T')"
              >
                <div class="wz wz2">厚度</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.T"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{ width: '30%', margin: '0 10px' }"
                v-if="spObj.hasOwnProperty('Φ')"
              >
                <div class="wz wz2">偏心直径</div>
                <el-input
                  class="sr sr2"
                  placeholder="单位mm(选填)"
                  v-model="spObj.Φ"
                  clearable
                >
                </el-input>
              </div>
              <div
                class="ys"
                :style="{
                  width: '10%',
                  margin: '0 10px',
                  display: 'flex',
                  justifyContent: 'flex-start',
                }"
              >
                <el-button type="primary" @click="pj(edit1)"
                  >生成规格</el-button
                >
              </div>
            </div>
          </div>
          <div class="relate">
            <el-popover placement="left" :width="400" trigger="click">
              <template #reference>
                <el-button style="margin-right: 16px" @click="relate(edit1)"
                  >选择关联开炉记录</el-button
                >
              </template>
              <el-table :data="gridData" @row-click="handleRowClick">
                <el-table-column
                  prop="furnaceNumber"
                  label="炉号"
                  width="120"
                />
                <el-table-column
                  prop="furnaceDate"
                  label="生产时间"
                  width="150"
                >
                </el-table-column>
                <el-table-column prop="modelName" label="合金牌号" width="120">
                </el-table-column>
              </el-table>
            </el-popover>
            <el-alert title="非必选" type="info"  class="tip" style="width:10%;height:30px" :closable="false"/>
            <div class="col">
              <div class="ys">
                <div class="wz">熔炼炉号</div>
                <el-input
                  class="sr"
                  placeholder="熔炼炉号"
                  v-model="edit1.furnaceRecord.furnaceNumber"
                  disabled
                >
                </el-input>
              </div>
              <div class="ys">
                <div class="wz">生产日期</div>
                <el-input
                  class="sr"
                  placeholder="开炉生产日期"
                  v-model="edit1.furnaceRecord.furnaceDate"
                  disabled
                >
                </el-input>
              </div>
            </div>
            <div class="col">
              <div class="ys">
                <div class="wz">总投入量</div>
                <el-input
                  class="sr"
                  placeholder="原材料总投入量"
                  v-model="edit1.furnaceRecord.totalConsumed"
                  disabled
                >
                </el-input>
              </div>
              <div class="ys">
                <div class="wz">总产出量</div>
                <el-input
                  class="sr"
                  placeholder="熔炼总产出量"
                  v-model="edit1.furnaceRecord.output"
                  disabled
                >
                </el-input>
              </div>
            </div>
            <div class="col">
              <div class="ys">
                <div class="wz">平均损耗</div>
                <el-input
                  class="sr"
                  placeholder="熔炼平均损耗"
                  v-model="edit1.furnaceRecord.avgLoss"
                  disabled
                >
                </el-input>
              </div>
              <div class="ys">
                <div class="wz">产出率</div>
                <el-input
                  class="sr"
                  placeholder="熔炼产出率"
                  v-model="edit1.furnaceRecord.outputRatio"
                  disabled
                >
                </el-input>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitB">确 定</el-button>
          <el-button @click="reset2">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="关联开炉记录"
        v-model="dialogFormVisible2"
        :before-close="reset3"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        draggable
      >
        <div class="col">
          <div class="ys">
            <div class="wz">熔炼炉号</div>
            <el-input
              class="sr"
              placeholder="无数据"
              v-model="reMel.furnaceNumber"
              disabled
            >
            </el-input>
          </div>
          <div class="ys">
            <div class="wz">生产日期</div>
            <el-input
              class="sr"
              placeholder="无数据"
              v-model="reMel.furnaceDate"
              disabled
            >
            </el-input>
          </div>
        </div>
        <div class="col">
          <div class="ys">
            <div class="wz">总投入量</div>
            <el-input
              class="sr"
              placeholder="无数据"
              v-model="reMel.totalConsumed"
              disabled
            >
            </el-input>
          </div>
          <div class="ys">
            <div class="wz">总产出量</div>
            <el-input
              class="sr"
              placeholder="无数据"
              v-model="reMel.output"
              disabled
            >
            </el-input>
          </div>
        </div>
        <div class="col">
          <div class="ys">
            <div class="wz">平均损耗</div>
            <el-input
              class="sr"
              placeholder="无数据"
              v-model="reMel.avgLoss"
              disabled
            >
            </el-input>
          </div>
          <div class="ys">
            <div class="wz">产出率</div>
            <el-input
              class="sr"
              placeholder="无数据"
              v-model="reMel.outputRatio"
              disabled
            >
            </el-input>
          </div>
        </div>
      </el-dialog>

      <el-dialog
        title="计划完成入库"
        v-model="dialogFormVisible3"
        :before-close="reset4"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="460px"
        draggable
      >
        <div class="form-box">
          <div class="col">
            <div class="ys">
              <div class="wz">操作人员</div>
              <el-input
                class="sr"
                placeholder="姓名"
                v-model="operatorName"
                disabled
              >
              </el-input>
            </div>
          </div>
          <div class="col">
            <div class="ys">
              <div class="wz">合金牌号</div>
              <el-input
                class="sr"
                placeholder="合金牌号"
                v-model="storeData.modelName"
                disabled
              >
              </el-input>
            </div>
          </div>
          <div class="col">
            <div class="ys">
              <div class="wz">合金规格</div>
              <el-input
                class="sr"
                placeholder="合金规格"
                v-model="storeData.specification"
                disabled
              >
              </el-input>
            </div>
          </div>
          <div v-if="storeData.isQuantityBased == 1">
            <div class="col">
              <div class="ys">
                <div class="wz">入库重量</div>
                <el-input
                  class="sr"
                  placeholder="入库重量(主要必填)"
                  v-model="storeData.amount"
                  clearable
                >
                </el-input>
              </div>
            </div>
            <div class="col">
              <div class="ys">
                <div class="wz">入库件数</div>
                <el-input
                  class="sr"
                  placeholder="入库件数(选填作辅助)"
                  v-model="storeData.piece"
                  clearable
                >
                </el-input>
              </div>
            </div>
          </div>
          <div class="col" v-else>
            <div class="ys">
              <div class="wz">入库件数</div>
              <el-input
                class="sr"
                placeholder="入库件数"
                v-model="storeData.piece"
                clearable
              >
              </el-input>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitC">确 定</el-button>
          <el-button @click="reset4">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="备注"
        v-model="dialogFormVisible4"
        width="20%"
        draggable
      >
        {{ note }}
      </el-dialog>

      <div class="load" v-if="loading">
        <el-icon class="is-loading">
          <Loading />
        </el-icon>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import request from "@/utils/request";
import { useRoute } from "vue-router";
export default defineComponent({
  setup() {
    const state = reactive({
      operatorId: 1,
      operatorName: "",
      loading: false,
      search: false,
      startDate: "",
      endDate: "",
      modelName: "",
      pageNum: 1,
      total: 0,
      pageSize: 30,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      dialogFormVisible4: false,
      tableData: [],
      restaurants: [],
      selectedRows: [],
      form: {
        modelId: "",
        modelName: "",
        plannedQuantity: "",
        note: "",
        specification: "",
        specifications: [],
        isSpecificationType: "",
        isQuantityBased: 0,
        furnaceRecord: {},
      },
      edit: {},
      edit1: {},
      gridData: [],
      reMel: {}, //关联开炉记录展示
      storeData: {},
      note: "",
      dy: ["其他", "板", "管", "棒", "镜", "环", "电焊针"],
      options: [
        {
          value: 3,
          label: "棒(stick)",
        },
        {
          value: 2,
          label: "管(tube)",
        },
        {
          value: 1,
          label: "板(board)",
        },
        {
          value: 4,
          label: "镜(mirror)",
        },
        {
          value: 5,
          label: "环(circle)",
        },
        {
          value: 6,
          label: "电焊针(needle)",
        },
        {
          value: 7,
          label: "其他(other)",
        },
      ],
      types: [
        {
          value: 0,
          label: "产品(按件数计)",
        },
        {
          value: 1,
          label: "材料(重量为主，件数为辅)",
        },
      ],
      spObj: {},
    });
    const pj = (form) => {
      const result = Object.entries(state.spObj)
        .map(([key, value]) => `${key}${value}`)
        .join("*");
      form.specification = result;
    };
    const handleChange = (form) => {
      state.spObj = {};
      switch (form.isSpecificationType) {
        case 3:
          state.spObj.D = "";
          state.spObj.L = "";
          break;
        case 2:
          state.spObj.D = "";
          state.spObj.d = "";
          state.spObj.L = "";
          break;
        case 1:
          state.spObj.L = "";
          state.spObj.W = "";
          state.spObj.T = "";
          break;
        case "线":
          state.spObj.D = "";
          break;
        case "带":
          state.spObj.W = "";
          state.spObj.T = "";
          break;
        case 4:
          state.spObj.D = "";
          state.spObj.T = "";
          break;
        case 5:
          state.spObj.D = "";
          state.spObj.d = "";
          break;
        case 6:
          state.spObj.D = "";
          state.spObj.L = "";
          state.spObj.Φ = "";
          break;
      }
    };
    const querySearch1 = (queryString, cb) => {
      const results = queryString
        ? createFilter1(queryString, state.restaurants)
        : state.restaurants;
      cb(results);
    };
    const createFilter1 = (queryString, restaurants) => {
      return restaurants.filter((item) =>
        item.modelName.toLowerCase().includes(queryString.toLowerCase())
      );
    };
    const reset = () => {
      state.modelName = "";
      state.startDate = "";
      state.endDate = "";
    };
    const reset1 = () => {
      state.form.modelId = "";
      state.form.modelName = "";
      state.form.plannedQuantity = "";
      state.form.note = "";
      state.form.isSpecificationType = "";
      state.form.isQuantityBased = 0;
      state.form.specification = "";
      state.form.specifications = [];
      state.form.furnaceRecord = {};
      state.spObj = {};
      state.dialogFormVisible = false;
    };
    const reset2 = () => {
      state.edit1 = {};
      state.edit1.furnaceRecord = {};
      state.spObj = {};
      state.dialogFormVisible1 = false;
    };
    const reset3 = () => {
      state.reMel = {};
      state.dialogFormVisible2 = false;
    };
    const reset4 = () => {
      state.storeData = {};
      state.dialogFormVisible3 = false;
    };
    const relate = async (obj) => {
      try {
        const response = await request({
          method: "post",
          url: "/product/furnace/records/page",
          data: {
            modelName: obj.modelName,
            startDate: "",
            endDate: "",
          },
          headers: {
            "Content-Type": "application/json",
          },
        });
        if (response.data.success) {
          state.gridData = response.data.data.list;
          for (let i = 0; i < state.gridData.length; i++) {
            state.gridData[i].furnaceDate = state.gridData[i].furnaceDate
              .split("T")
              .join(" ");
          }
        } else {
          ElMessage({
            showClose: true,
            message: response.data.errorMsg,
            type: "error",
          });
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    };
    const handleSelect = (item) => {
      state.modelName = item.modelName;
    };
    const handleSelect1 = (item) => {
      state.form.modelName = item.modelName;
      state.form.modelId = item.id;
      state.form.specifications = item.specifications;
    };
    const handleSelect2 = (item) => {
      state.edit1.modelName = item.modelName;
      state.edit1.modelId = item.id;
      state.edit1.specifications = item.specifications;
    };
    const showAllSuggestions = (queryString, cb) => {
      cb(state.form.specifications); // 始终返回完整数组
    };
    const handleSelect3 = (item) => {
      state.form.specification = item;
    };
    const showAllSuggestions1 = (queryString, cb) => {
      cb(state.edit1.specifications); // 始终返回完整数组
    };
    const handleSelect4 = (item) => {
      state.edit1.specification = item;
    };
    const getR = async () => {
      try {
        const response = await request({
          method: "get",
          url: "/product/alloy/models/all",
          headers: {
            "Content-Type": "application/json",
          },
        });
        state.restaurants = response.data.data;
      } catch (error) {
        console.error("请求失败:", error);
      }
    };
    const handleReturn = () => {
      state.search = false;
      handleRefresh();
    };
    const handleSearch = async () => {
      state.loading = true;
      try {
        const response = await request({
          method: "post",
          url: "/product/plans/page",
          data: {
            modelName: state.modelName,
            startDate: state.startDate.split(" ").join("T"),
            endDate: state.endDate.split(" ").join("T"),
          },
          headers: {
            "Content-Type": "application/json",
          },
        });
        if (response.data.success) {
          if (!state.search)
            ElMessage({
              showClose: true,
              message: "查询完成",
              type: "success",
            });
          state.search = true;
          state.tableData = response.data.data.list;
          for (let i = 0; i < state.tableData.length; i++) {
            state.tableData[i].updatedAt = state.tableData[i].updatedAt
              .split("T")
              .join(" ");
            state.tableData[i].createdAt = state.tableData[i].createdAt
              .split("T")
              .join(" ");
          }
          state.loading = false;
        } else {
          ElMessage({
            showClose: true,
            message: response.data.errorMsg,
            type: "error",
          });
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    };
    const handleRefresh = async () => {
      if (state.search == false) {
        state.loading = true;
        try {
          const response = await request({
            method: "post",
            url: "/product/plans/page",
            data: {
              pageSize: state.pageSize,
              pageNum: state.pageNum,
            },
            headers: {
              "Content-Type": "application/json",
            },
          });
          state.tableData = response.data.data.list;
          for (let i = 0; i < state.tableData.length; i++) {
            state.tableData[i].updatedAt = state.tableData[i].updatedAt
              .split("T")
              .join(" ");
            state.tableData[i].createdAt = state.tableData[i].createdAt
              .split("T")
              .join(" ");
          }
          state.total = response.data.data.total;
          state.loading = false;
          getR();
        } catch (error) {
          console.error("请求失败:", error);
        }
      } else handleSearch();
    };
    const handleDel = async () => {
      const ids = [];
      for (let i = 0; i < state.selectedRows.length; i++) {
        ids.push(state.selectedRows[i].id); // 直接修改正在遍历的数组
      }
      if (
        state.selectedRows.length == state.tableData.length &&
        state.pageNum > 1
      )
        state.pageNum--;
      try {
        const response = await request({
          method: "delete",
          url: "/product/plans",
          data: {
            ids: ids,
          },
          headers: {
            "Content-Type": "application/json",
          },
        });
        if (response.data.success) {
          ElMessage({
            showClose: true,
            message: "删除成功",
            type: "success",
          });
          handleRefresh();
        } else {
          ElMessage({
            showClose: true,
            message: response.data.errorMsg,
            type: "error",
          });
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    };
    const handleDelete = async () => {
      if (state.selectedRows.length == 0) {
        ElMessage({
          showClose: true,
          message: "您还未选择您要删除的记录",
          type: "warning",
        });
      } else {
        ElMessageBox.confirm("选择的记录将被删除,要继续吗?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            handleDel();
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "删除取消",
            });
          });
      }
    };
    const handleRowClick = (row) => {
      state.edit1.furnaceRecord = row;
    };
    const handleRowClick1 = (row) => {
      state.form.furnaceRecord = row;
    };
    const submitA = async () => {
      if (
        state.form.modelName === "" ||
        state.form.plannedQuantity === "" ||
        state.form.isSpecificationType === ""
      )
        valid();
      else {
        try {
          const response = await request({
            method: "post",
            url: "/product/plans",
            data: {
              modelId: state.form.modelId,
              modelName: state.form.modelName,
              note: state.form.note,
              plannedQuantity: Number(state.form.plannedQuantity),
              specification: state.form.specification,
              isSpecificationType: state.form.isSpecificationType,
              furnaceRecordId: state.form.furnaceRecord.id,
              isQuantityBased:state.form.isQuantityBased
            },
            headers: {
              "Content-Type": "application/json",
            },
          });
          if (response.data.success) {
            ElMessage({
              showClose: true,
              message: "添加成功",
              type: "success",
            });
            reset1();
            handleRefresh();
          } else {
            ElMessage({
              showClose: true,
              message: response.data.errorMsg,
              type: "error",
            });
          }
        } catch (error) {
          console.error("请求失败:", error);
        }
      }
    };
    const submitB = async () => {
      if (state.edit1.plannedQuantity === "" || state.edit1.modelName === "")
        valid1();
      else {
        try {
          const response = await request({
            method: "put",
            url: "/product/plans",
            data: {
              id: state.edit1.id,
              modelId: state.edit1.modelId,
              modelName: state.edit1.modelName,
              note: state.edit1.note,
              status: state.edit1.status,
              plannedQuantity: state.edit1.plannedQuantity,
              furnaceRecordId: state.edit1.furnaceRecord.id,
              specification: state.edit1.specification,
              isSpecificationType: state.edit1.isSpecificationType,
              isQuantityBased: state.edit1.isQuantityBased,
            },
            headers: {
              "Content-Type": "application/json",
            },
          });
          if (response.data.success) {
            reset2();
            ElMessage({
              showClose: true,
              message: "编辑成功",
              type: "success",
            });
            handleRefresh();
          } else {
            ElMessage({
              showClose: true,
              message: response.data.errorMsg,
              type: "error",
            });
          }
        } catch (error) {
          console.error("请求失败:", error);
        }
      }
    };
    const submitC = async () => {
      if (
        (state.storeData.isQuantityBased == 1 &&
          state.storeData.amount === "") ||
        (state.storeData.isQuantityBased == 0 && state.storeData.piece === "")
      )
        valid2();
      else {
        try {
          const response = await request({
            method: "post",
            url: "/product/inventory/stock-in",
            data: {
              producePlanId: state.storeData.id,
              productId: state.storeData.modelId,
              modelName: state.storeData.modelName,
              operatorId: state.operatorId,
              operatorName: state.operatorName,
              amount: state.storeData.amount,
              piece: state.storeData.piece,
              specification: state.storeData.specification,
            },
            headers: {
              "Content-Type": "application/json",
            },
          });
          if (response.data.success) {
            reset4();
            ElMessage({
              showClose: true,
              message: "入库成功",
              type: "success",
            });
            handleRefresh();
          } else {
            ElMessage({
              showClose: true,
              message: response.data.errorMsg,
              type: "error",
            });
          }
        } catch (error) {
          console.error("请求失败:", error);
        }
      }
    };
    const handleEdit = (row) => {
      console.log(row.isSpecificationType);
      state.edit = row;
      state.edit1.isQuantityBased = row.isQuantityBased;
      state.edit1.id = row.id;
      state.edit1.modelId = row.modelId;
      state.edit1.note = row.note;
      state.edit1.plannedQuantity = row.plannedQuantity;
      state.edit1.modelName = row.modelName;
      state.edit1.status = row.status;
      state.edit1.specification = row.specification;
      state.edit1.isSpecificationType = row.isSpecificationType;
      handleChange(state.edit1);
      if (row.furnaceRecord == null) state.edit1.furnaceRecord = {};
      else {
        state.edit1.furnaceRecord = row.furnaceRecord;
        state.edit1.furnaceRecord.furnaceDate =
          state.edit1.furnaceRecord.furnaceDate.split("T").join(" ");
      }
      state.dialogFormVisible1 = true;
    };
    const handleSelectionChange = (selected) => {
      state.selectedRows = selected; // 更新选中的行
    };
    const handleConcrete = (row) => {
      if (row.furnaceRecord != null) {
        state.reMel = row.furnaceRecord;
        state.reMel.furnaceDate = state.reMel.furnaceDate.split("T").join(" ");
      }
      state.dialogFormVisible2 = true;
    };
    const handleConcrete1 = (row) => {
      state.note = row.note;
      state.dialogFormVisible4 = true;
    };
    const handleStore = (row) => {
      state.storeData.id = row.id;
      state.storeData.isQuantityBased = row.isQuantityBased;
      state.storeData.modelName = row.modelName;
      state.storeData.modelId = row.modelId;
      state.storeData.amount = "";
      state.storeData.piece = "";
      state.storeData.specification = row.specification;
      state.dialogFormVisible3 = true;
    };
    const valid = () => {
      if (state.form.modelName === "") {
        ElMessage({
          showClose: true,
          message: "合金牌号不能为空",
          type: "warning",
        });
      } else if (state.form.plannedQuantity === "") {
        ElMessage({
          showClose: true,
          message: "请填写需求量",
          type: "warning",
        });
      } else if (state.form.isSpecificationType === "") {
        ElMessage({
          showClose: true,
          message: "请选择一种物品形态",
          type: "warning",
        });
      }
    };
    const valid1 = () => {
      if (state.edit1.modelName === "") {
        ElMessage({
          showClose: true,
          message: "合金牌号不能为空",
          type: "warning",
        });
      } else if (state.edit1.plannedQuantity === "") {
        ElMessage({
          showClose: true,
          message: "请填写需求量",
          type: "warning",
        });
      }
    };
    const valid2 = () => {
      if (
        state.storeData.isQuantityBased == 0 &&
        state.storeData.piece === ""
      ) {
        ElMessage({
          showClose: true,
          message: "请填写入库件数",
          type: "warning",
        });
      } else if (
        state.storeData.isQuantityBased == 1 &&
        state.storeData.amount === ""
      ) {
        ElMessage({
          showClose: true,
          message: "请填写入库重量",
          type: "warning",
        });
      }
    };
    onMounted(() => {
      state.operatorName=useRoute().params.userName;
      handleRefresh();
    });
    return {
      ...toRefs(state),
      pj,
      reset,
      reset1,
      reset2,
      reset3,
      reset4,
      relate,
      querySearch1,
      handleChange,
      handleRefresh,
      handleSelect,
      handleSelect1,
      handleSelect2,
      handleSelect3,
      handleSelect4,
      handleSearch,
      handleReturn,
      handleDelete,
      handleSelectionChange,
      handleEdit,
      handleRowClick,
      handleRowClick1,
      handleConcrete,
      handleConcrete1,
      handleStore,
      submitA,
      submitB,
      submitC,
      showAllSuggestions,
      showAllSuggestions1,
    };
  },
});
</script>

<style scoped>
.layout {
  width: 100%;
  height: 100%;
  background-color: #f5f6f9;
  padding-top: 20px;
}
.main-box {
  width: 98%;
  min-height: 800px;
  height: auto;
  background-color: #ffffff;
  margin: auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.tit {
  height: 40px;
  line-height: 40px;
  font-weight: 600;
  font-size: 20px;
  text-indent: 1em;
}
.searcher-box {
  margin-top: 20px;
  height: 100px;
  width: 96%;
  margin-left: auto;
  margin-right: auto;
  display: flex;
}
.inp {
  height: 50px;
  width: 30%;
  display: flex;
  overflow: hidden;
  line-height: 30px;
}
.inpH {
  width: 20%;
  margin-left: 5px;
  margin-right: 5px;
  text-align: center;
}
.btn-list {
  border: 1px solid #e1e3e5;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  margin: 0 20px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  overflow: hidden;
}
.table-box {
  flex: 1;
  margin: 0 20px;
  border: none;
}
.el-table {
  --el-table-header-bg-color: var(--el-bg-color-page);
  --el-table-border-color: var(--el-border-color-dark);
  --el-table-header-text-color: var(--el-text-color-primary);
}
.pagination-box {
  margin: 10px 20px;
  display: flex;
  justify-content: flex-end;
}
.form-box {
  position: relative;
  min-height: 180px;
  height: auto;
  overflow: hidden;
}
.col {
  height: 32px;
  display: flex;
  background-color: white;
  justify-content: space-between;
  margin-bottom: 10px;
}
.ys {
  width: 400px;
  display: flex;
  justify-content: space-around;
}
.wz {
  width: 20%;
  line-height: 32px;
  font-weight: 600;
}
.sr {
  display: flex;
  width: 70%;
  height: 32px;
  justify-content: space-around;
}
.col1 {
  height: 100px;
}
.ys1 {
  height: 100px;
}
.wz1 {
  height: 32px;
}
.sr1 {
  height: 100px;
}
.el-textarea__inner {
  height: 100px;
}
.relate {
  position: relative;
  border: 1px #e1e3e5 solid;
  min-height: 50px;
  height: auto;
  border-radius: 5px;
  margin-top: 20px;
  margin-bottom: 10px;
}
.el-tooltip__trigger {
  margin: 10px;
}
.load {
  position: absolute;
  top: 450px;
  left: 800px;
  width: 40px;
  height: 40px;
  border-radius: 5px;
  color: white;
  background-color: rgba(0, 0, 0, 0.68);
  line-height: 40px;
  text-align: center;
  z-index: 9999;
}
.el-icon.is-loading {
  animation: rotating 2s linear infinite;
}
@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.sp {
  display: flex;
  min-height: 32px;
  height: auto;
  margin-bottom: 10px;
}
.sr2 {
  width: 72%;
}
.wz2 {
  width: 28%;
  text-align: center;
}
.tip {
  position: absolute;
  top: 10px;
  left: 200px;
  width: 50%;
  height: 35px;
}
</style>